﻿using Farming.Domain;
using Farming.Repositories;
using IdentityModel;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Farming.WebApi.Filter
{
    public class CustomActionFilterAttribute : IAsyncActionFilter
    {
        
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 在执行操作之前调用
            if (context.ActionDescriptor.EndpointMetadata.Any(em => em.GetType() == typeof(SkipFilterAttribute)))
            {
                // 如果操作方法有SkipFilterAttribute特性，则跳过过滤器的执行
                return;
            }


            var result= await next();
            var name = result.HttpContext.User.FindFirst(JwtClaimTypes.Name)?.Value;
            if (name == null)
            {
                return;
            }
            //var id= context.HttpContext.User.FindFirst(JwtClaimTypes.Id).Value;
           var log= result.HttpContext.RequestServices.GetRequiredService<IRepository<LogMessage>>();
            LogMessage logMessage = new LogMessage()
            {
                AccessTime = DateTime.Now,
                LogPath = result.HttpContext.Request.Path,
                UserName = name,
                LogType = LogEnumHelper.GetDescription(LogEnum.AccessSuccess)
            };
            int e= await log.InSertAsync(logMessage);

        }
    }
}
